package com.dean.service.impl;

import com.dean.dynamicexe.service.ComputerScriptService;
import com.dean.entity.DeanResponse;
import com.dean.exception.DeanRuntimeException;
import com.dean.service.support.AbstractDeanScriptService;
import com.dean.utils.FileUtils;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName DeanGroovyService
 * @Description groovy 脚本服务
 * @Author dean
 * @Date 2021/10/3 10:03
 */
public class DeanGroovyClassService extends AbstractDeanScriptService {

    @Override
    public DeanResponse call(String script, Map<String, Object> parameters) {
        DeanResponse res = DeanResponse.ok();
        try {
            GroovyClassLoader classLoader = new GroovyClassLoader();
            Class<ComputerScriptService> groovyClass = classLoader.parseClass(script);
            ComputerScriptService service = groovyClass.newInstance();
            Map<String,Object> params = init();
            params.putAll(parameters);
            res = service.call(params);
        } catch (InstantiationException | IllegalAccessException e) {
            DeanRuntimeException.throwException(996,e.getMessage(),e);
        }
        return res;
    }

//    public static void main(String[] args) throws IOException {
//        DeanGroovyClassService groovyService = new DeanGroovyClassService();
//        Map<String,Object> params =  new HashMap<>();
//        System.out.println(DeanGroovyClassService.class.getClassLoader().getResource(""));
//        File file  = new File(DeanGroovyClassService.class.getClassLoader().getResource("").getPath()+"scripts/hello.groovy");
//        System.out.println(FileUtils.readFile(file.getPath()));
//        groovyService.call(FileUtils.readFile(file.getPath()),params);
//        //groovyService.call("def call(Map<String,Object> params){println(params); return 1}",params);
//    }


}
